package middleware

import (
	"camera_app/entity"
	"camera_app/utils"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func StaticAuth(ctx *gin.Context) {
	var auth, querErr = ctx.GetQuery("token")
	fmt.Print(auth, querErr)
	if auth == "" {
		ctx.JSON(http.StatusUnauthorized, gin.H{"msg": "no auth", "data": nil})
		ctx.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	claims, err := utils.ParseToken(auth)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{"msg": "auth error", "data": nil})
		ctx.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	var user entity.User
	if c, ok := claims.(jwt.MapClaims); ok {
		user.Username = c["username"].(string)
		user.Password = c["password"].(string)
		user.UserId = int(c["userId"].(float64))
	}
	ctx.Set("user", user)
	username := ctx.Param("username")
	if username != user.Username {
		ctx.JSON(http.StatusUnauthorized, gin.H{"msg": "auth error", "data": nil})
		ctx.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	ctx.Next()

}
